
<template>
  <div>
    <div>{{ message }}</div>
    <button @click="changeMsg">响应式</button>

    <div>{{ message2 }}</div>
    <button @click="changeMsg2">非响应式</button>
    <button @click="changeMsg3">非响应式，强制刷新</button>

    <div>{{ message4 }}</div>
    <button @click="changeMsg4">自定义响应式</button>

    <div>{{ message5.name }}{{message5.test.toString()}}</div>
    <button @click="changeMsg5">自定义响应式整体对象</button>
    <button @click="changeMsg6">自定义响应式单个对象</button>
  </div>
</template>
 
<script setup lang="ts">
import { Ref, ref, triggerRef, shallowRef, customRef, computed } from "vue";
type Obj = {
  name: string;
};

let message: Ref<Obj> = ref({
  name: "小满",
});

const changeMsg = () => {
  message.value.name = "大满";
  // triggerRef(message)
};

let message2: Ref<Obj> = shallowRef({
  name: "非响应式",
});
const changeMsg2 = () => {
  message2.value.name = "非响应式";
};
const changeMsg3 = () => {
  message2.value.name = "非响应式，强制刷新";
  triggerRef(message2);
};

function MyFun(value) {
  return customRef((track, trigger) => {
    return {
      get() {
        track();
        console.log("track" + JSON.stringify(value));
        return value;
      },
      set(newValue) {
        console.log(
          "value:" + JSON.stringify(value) + "---" + JSON.stringify(newValue)
        );
        value = newValue;
        console.log(
          "value:" + JSON.stringify(value) + "---" + JSON.stringify(newValue)
        );
        trigger();
      },
    };
  });
}
let message4 = MyFun("自定义响应式");
const changeMsg4 = () => {
  message4.value = "自定义被刷新了";
  // triggerRef(message4)
};

// customRef可以绑定基础数据类型
function MyFun2(value) {
  return customRef((track, trigger) => {
    return {
      get() {
        track();
        console.log("track" + JSON.stringify(value));
        return value;
      },
      set(newValue) {
        console.log(
          "value:" + JSON.stringify(value) + "---" + JSON.stringify(newValue)
        );
        value = newValue;
        console.log(
          "value:" + JSON.stringify(value) + "---" + JSON.stringify(newValue)
        );
        trigger();
      },
    };
  });
}
let message5 = MyFun2({
  name: "自定义响应式",
  test: ["1", "2"],
});
const changeMsg5 = () => {
  message5.value = {
    name: "自定义整体被刷新了",
    test: ["3", "4"],
  };
  // triggerRef(message4)
  //   源码也是调用 reactive  
};
const changeMsg6 = () => {
  message5.value.name = "自定义单体被刷新了";
  //单个属性没法刷新
  // triggerRef(message4)
};
</script>
 
 
<style>
</style>